<!--#layout("/common/layout.html"){ -->
<label class="layui-form-label">
   等待接入:
</label>
<div class="layui-input-inline">
    <span style="line-height:38px;margin-left:8px;" id="sizeSpan">
         ${waitQueueSize}
    </span>
</div>
<br/>
<button class="layui-btn " type="button" id="addButton">接入</button>
<button class="layui-btn layui-bg-cyan" type="button" id="leave">暂离</button>
<button class="layui-btn layui-btn-danger" type="button" id="offline">下线</button>
<br/>
<br/>
<!--<div class="layui-input-inline">-->
<!--    <input type="text" name="nickName" id="nickName" autocomplete="off" maxlength="20" class="layui-input">-->
<!--</div>-->
<!--<button class="layui-btn " type="button" id="setButton">设置昵称</button>-->
<!--#} -->
<script>
    layui.use('layim', function(layim){
        var $ = layui.jquery;
        var path = window.location.host;
        var userId = "${userId}";
        var websocket =  null;
        //当前聊天窗口用户id
        var chatId ;
        var closeWebsocket = false;
        createWebsocket();
        function initCusMsg(data){
            $.each(data,function(i,v){
                layim.chat({
                    name: v.name //名称
                    ,type: 'friend' //聊天类型
                    ,avatar:  v.avatar //头像
                    ,id: v.id //好友id
                })
                var arr = new Array();
                arr = v.list;
                $.each(arr,function(index,value){
                    var username = "客服";
                    var avatar = "http://static.51sdx.com/p/html/kefu/kefu.png";
                    if(value.msgClass==1){
                        username = v.name;
                        avatar =v.avatar;
                    }
                    layim.getMessage({
                        username: username //名称
                        ,type: 'friend' //聊天类型
                        ,avatar: avatar  //头像
                        ,id: v.id //好友id
                        ,content: value.safeContent
                        ,cid: 0 //消息id，可不传。除非你要对消息进行一些操作（如撤回）
                        ,mine: false //是否我发送的消息，如果为true，则会显示在右方
                        ,fromid:  v.id  //消息的发送者id（比如群组中的某个消息发送者），可用于自动解决浏览器多窗口时的一些问题
                        ,timestamp: new Date(value.createTime).getTime()
                    })
                });
            });
        }

        //接入
        $("#addButton").click(function(){
            //重新建立连接
            if(closeWebsocket){
                createWebsocket();
            }

            $.ajax({
                type: 'POST',
                url: '${ctxPath}/crm/chat/getCus.json',
                data: {},
                async: false,
                dataType:'json',
                success: function(res){
                    if(res.code==0){
                        initCusMsg(res.data);
                    }
                }
            });
        });

        //暂离
        $("#leave").click(function(){
                $.ajax({
                    type: 'POST',
                    url: '${ctxPath}/crm/chat/leave.json',
                    data: {},
                    async: false,
                    dataType:'json',
                    success: function(res){
                        if(res.code==0){
                            Common.info("操作成功");
                        }
                    }
                });
        });

        //下线
        $("#offline").click(function(){
            websocket.close();
            $.ajax({
                type: 'POST',
                url: '${ctxPath}/crm/chat/offline.json',
                data: {},
                async: false,
                dataType:'json',
                success: function(res){

                }
            });
        });

        //设置昵称
        $("#setButton").click(function(){
            var nickName = $("#nickName").val();
            console.log(nickName);
            if(nickName){
                $.ajax({
                    type: 'POST',
                    url: '${ctxPath}/crm/chat/setNickName.json',
                    data: {nickName:nickName},
                    async: false,
                    dataType:'json',
                    success: function(res){
                        if(res.code==0){
                            Common.info("操作成功");
                        }
                    }
                });
            }
        });

        //演示自动回复
        var autoReplay = [
            '您好，我现在有事不在，一会再和您联系。',
            '你好，我是主人的美女秘书，有什么事就跟我说吧，等他回来我会转告他的。face[心] face[心] face[心] ',
            '你要和我说话？你真的要和我说话？你确定自己想说吗？你一定非说不可吗？那你说吧，这是自动回复。'
        ];

        //基础配置
        layim.config({

            //初始化接口
            init: {
                url:'${ctxPath}/crm/chat/getList.json'
                ,data: {}
            }
            //上传图片接口
            // ,uploadImage: {
            //     url: '/upload/image' //（返回的数据格式见下文）
            //     ,type: '' //默认post
            // }

            // //上传文件接口
            // ,uploadFile: {
            //     url: '/upload/file' //（返回的数据格式见下文）
            //     ,type: '' //默认post
            // }

            //扩展工具栏
            ,tool: [
                {
                    alias: 'info' //工具别名
                    ,title: '购买记录' //工具名称
                    ,icon: '&#xe615;' //工具图标，参考图标文档
                },
                {
                    alias: 'cust' //工具别名
                    ,title: '用户信息' //工具名称
                    ,icon: '&#xe66f;' //工具图标，参考图标文档
                }
            ]

            ,brief: true //是否简约模式（若开启则不显示主面板）

            //,title: 'WebIM' //自定义主面板最小化时的标题
            //,right: '100px' //主面板相对浏览器右侧距离
            //,minRight: '90px' //聊天面板最小化时相对浏览器右侧距离
            ,initSkin: '5.jpg' //1-5 设置初始背景
            //,skin: ['aaa.jpg'] //新增皮肤
            //,isfriend: false //是否开启好友
            ,isgroup: false //是否开启群组
            // ,min: true //是否始终最小化主面板，默认false
            ,notice: false //是否开启桌面消息提醒，默认false
            ,voice: false //声音提醒，默认开启，声音文件为：default.wav
            ,copyright: true
            // ,msgbox: layui.cache.dir + 'css/modules/layim/html/msgbox.html' //消息盒子页面地址，若不开启，剔除该项即可
            // ,find: layui.cache.dir + 'css/modules/layim/html/find.html' //发现页面地址，若不开启，剔除该项即可
            ,chatLog: '${ctxPath}/crm/chat/chatLog.do' //聊天记录页面地址，若不开启，剔除该项即可

        });

        //监听聊天窗口的关闭
        layim.on('chatClose', function(res){
            var type = res.data.type;
        });

        //监听自定义工具栏点击，以添加代码为例
        layim.on('tool(code)', function(insert){
            layer.prompt({
                title: '插入代码'
                ,formType: 2
                ,shade: 0
            }, function(text, index){
                layer.close(index);
                insert('[pre class=layui-code]' + text + '[/pre]'); //将内容插入到编辑器
            });
        });

        layim.on('tool(info)', function(insert, send, obj){
            $.ajax({
                type: 'POST',
                url: '${ctxPath}/crm/chat/order.json',
                data: {sessionId:chatId},
                async: false,
                dataType:'json',
                success: function(res){
                    if(res.code==0){
                        var info = $('#infoCon');
                        if(!info || info.length==0){
                            var html =  '<div id="infoCon" class="right-container" style="width: 800px;height: 100%;position:absolute;top:0;right: -800px;background:#fff;padding: 20px 10px;box-sizing:border-box;font-size:14px;">'+
                                '<table cellspacing="0" cellpadding="0" border="0" class="layui-table">\n' +
                                '<tr>\n' +
                                ' <th align="center">订单Id</th>\n' +
                                ' <th align="center">订单名称</th>\n' +
                                ' <th align="center">订单类型</th>\n' +
                                ' <th align="center">订单状态</th>\n' +
                                ' <th align="center">支付时间</th>\n' +
                                '</tr>';
                                res.data.forEach(function(element) {
                                    html += '<tr>\n' +
                                    ' <td>'+ element.transactionId +'</td>\n' +
                                    ' <td align="center">'+ element.tradeMemo +'</td>\n' +
                                    ' <td align="center">'+ element.orderName +'</td>\n' +
                                    ' <td align="center">'+ element.payFlag +'</td>\n' +
                                    ' <td align="center">'+ element.payTime +'</td>\n' +
                                    '</tr>';
                                });

                            html += '</table>' +
                                '</div>';
                            $('.layui-layer-resize').after(html);
                        }else{
                            if(info.is(":hidden")){
                                info.show();
                            }else{
                                info.hide();
                            }
                        }
                    }
                }
            });
        });


        layim.on('tool(cust)', function(insert, send, obj){
            $.ajax({
                type: 'POST',
                url: '${ctxPath}/crm/chat/getCust.json',
                data: {sessionId:chatId},
                async: false,
                dataType:'json',
                success: function(res){
                    var phone = res.data.phone;
                    var choiceYearStr = "";
                    if(res.data.choiceYearStr!=null&&res.data.choiceYearStr!=''){
                        choiceYearStr = res.data.choiceYearStr;
                    }
                    var customerName ="";
                    if(res.data.customerName!=null&&res.data.customerName!=''){
                        customerName = res.data.customerName;
                    }
                    var provName ="";
                    if(res.data.provName!=null&&res.data.provName!=''){
                        provName = res.data.provName;
                    }
                    var sexStr ="";
                    if(res.data.sexStr!=null&&res.data.sexStr!=''){
                        sexStr = res.data.sexStr;
                    }
                    var schoolAddr ="";
                    if(res.data.highProvName!=null&&res.data.highProvName!=''){
                        schoolAddr += res.data.highProvName+" ";
                    }
                    if(res.data.cityName!=null&&res.data.cityName!=''){
                        schoolAddr += res.data.cityName+" ";
                    }
                    if(res.data.boroughName!=null&&res.data.boroughName!=''){
                        schoolAddr += res.data.boroughName;
                    }
                    var score ="";
                    if(res.data.score!=null&&res.data.score!=''){
                        score = res.data.score;
                    }
                    var rank ="";
                    if(res.data.rank!=null&&res.data.rank!=''){
                        rank = res.data.rank;
                    }

                    var majorTypeStr ="";
                    if(res.data.majorTypeStr!=null&&res.data.majorTypeStr!=''){
                        majorTypeStr = res.data.majorTypeStr;
                    }

                    var schoolName ="";
                    if(res.data.schoolName!=null&&res.data.schoolName!=''){
                        schoolName = res.data.schoolName;
                    }

                    if(res.code==0){
                        var cust = $('#custCon');
                        if(!cust || cust.length==0){
                            var html =  '<div id="custCon" class="right-container" style="width: 800px;height: 100%;position:absolute;top:0;right: -800px;background:#fff;padding: 20px 10px;box-sizing:border-box;font-size:14px;">'+
                               '<div class="layui-row">\n' +
                                '        <div class="layui-form-item">\n' +
                                '            <div class="layui-inline">\n' +
                                '            <label class="layui-form-label">登录账号</label>\n' +
                                '        <div class="layui-input-inline">\n' +
                                '               <input type="text" name="phone" id="phone" autocomplete="off" maxlength="50" class="layui-input" value="'+phone+'" readonly>\n' +
                                '        </div>\n' +
                                '            </div>\n' +
                                '            <div class="layui-inline">\n' +
                                '            <label class="layui-form-label">高考年份</label>\n' +
                                '        <div class="layui-input-inline">\n' +
                                '               <input type="text" name="choiceYearStr" id="choiceYearStr" autocomplete="off" maxlength="50" class="layui-input" value="'+choiceYearStr+'" readonly>\n' +
                                '        </div>\n' +
                                '            </div>\n' +
                                '        </div>\n' +
                                '</div>';
                            html +=  '<div class="layui-row">\n' +
                                '        <div class="layui-form-item">\n' +
                                '            <div class="layui-inline">\n' +
                                '            <label class="layui-form-label">账号昵称</label>\n' +
                                '        <div class="layui-input-inline">\n' +
                                '               <input type="text" name="customerName" id="customerName" autocomplete="off" maxlength="50" class="layui-input" value="'+customerName+'" readonly>\n' +
                                '        </div>\n' +
                                '            </div>\n' +
                                '            <div class="layui-inline">\n' +
                                '            <label class="layui-form-label">高考省份</label>\n' +
                                '        <div class="layui-input-inline">\n' +
                                '               <input type="text" name="provName" id="provName" autocomplete="off" maxlength="50" class="layui-input" value="'+provName+'" readonly>\n' +
                                '        </div>\n' +
                                '            </div>\n' +
                                '        </div>\n' +
                                '</div>';
                            html +=  '<div class="layui-row">\n' +
                                '        <div class="layui-form-item">\n' +
                                '            <div class="layui-inline">\n' +
                                '            <label class="layui-form-label">性别</label>\n' +
                                '        <div class="layui-input-inline">\n' +
                                '               <input type="text" name="sex" id="sex" autocomplete="off" maxlength="50" class="layui-input" value="'+sexStr+'" readonly >\n' +
                                '        </div>\n' +
                                '            </div>\n' +
                                '            <div class="layui-inline">\n' +
                                '            <label class="layui-form-label">高考科目</label>\n' +
                                '        <div class="layui-input-inline">\n' +
                                '               <input type="text" name="majorType" id="majorType" autocomplete="off" maxlength="50" class="layui-input" value="'+majorTypeStr+'" readonly>\n' +
                                '        </div>\n' +
                                '            </div>\n' +
                                '        </div>\n' +
                                '</div>';
                            html +=  '<div class="layui-row">\n' +
                                '        <div class="layui-form-item">\n' +
                                '            <div class="layui-inline">\n' +
                                '            <label class="layui-form-label">高中地址</label>\n' +
                                '        <div class="layui-input-inline">\n' +
                                '               <input type="text" name="schoolAddr" id="schoolAddr" autocomplete="off" maxlength="50" class="layui-input" value="'+schoolAddr+'" readonly>\n' +
                                '        </div>\n' +
                                '            </div>\n' +
                                '            <div class="layui-inline">\n' +
                                '            <label class="layui-form-label">高考分数</label>\n' +
                                '        <div class="layui-input-inline">\n' +
                                '               <input type="text" name="score" id="score" autocomplete="off" maxlength="50" class="layui-input" value="'+score+'" readonly>\n' +
                                '        </div>\n' +
                                '            </div>\n' +
                                '        </div>\n' +
                                '</div>';
                            html +=  '<div class="layui-row">\n' +
                                '        <div class="layui-form-item">\n' +
                                '            <div class="layui-inline">\n' +
                                '            <label class="layui-form-label">高中名称</label>\n' +
                                '        <div class="layui-input-inline">\n' +
                                '               <input type="text" name="schoolName" id="schoolName" autocomplete="off" maxlength="50" class="layui-input" value="'+schoolName+'" readonly>\n' +
                                '        </div>\n' +
                                '            </div>\n' +
                                '            <div class="layui-inline">\n' +
                                '            <label class="layui-form-label">高考位次</label>\n' +
                                '        <div class="layui-input-inline">\n' +
                                '               <input type="text" name="rank" id="rank" autocomplete="off" maxlength="50" class="layui-input" value="'+rank+'" readonly>\n' +
                                '        </div>\n' +
                                '            </div>\n' +
                                '        </div>\n' +
                                '</div>';
                            html +='</div>';
                            $('.layui-layer-resize').after(html);
                        }else{
                            if(cust.is(":hidden")){
                                cust.show();
                            }else{
                                cust.hide();
                            }
                        }
                    }
                }
            });
        });

        //监听layim建立就绪
        layim.on('ready', function(res){
            //console.log(res.mine);
            layim.msgbox(5); //模拟消息盒子有新消息，实际使用时，一般是动态获得

        });

        //监听发送消息
        layim.on('sendMessage', function(data){
            var To = data.to;
            var content = data.mine.content;
            var toId = To.id;
            var socketMsg = {msg:content,toUser:toId};
            websocket.send(JSON.stringify(socketMsg));

        });


        //监听聊天窗口的切换
        layim.on('chatChange', function(res){
            var type = res.data.type;
            var id = "#layui-badge-dot-"+res.data.id;
            $(id).toggleClass("layui-badge-dot",false);
            console.dir(res);
            chatId = res.data.id;
        });

        //初始化数据
        $(function () {
            $.ajax({
                type: 'POST',
                url: '${ctxPath}/crm/chat/initCusMsg.json',
                data: {},
                async: false,
                dataType:'json',
                success: function(res){
                    if(res.code==0){
                        initCusMsg(res.data);
                    }
                }
            });
        });

        //获取等待队列的人数
        function setWaitSize(){
            $.ajax({
                type: 'POST',
                url: '${ctxPath}/crm/chat/getWaitQueueSize.json',
                data: {},
                async: false,
                dataType:'json',
                success: function(res){
                    if(res.code==0){
                        $("#sizeSpan").text(res.data);
                    }else{
                        $("#sizeSpan").text(0);
                    }
                    setTimeout(function(){
                        setWaitSize();
                    },1000);
                }
            });
        }

        setTimeout(function(){
            setWaitSize();
        },1000);

        //创建websocket连接
        function createWebsocket(){
            websocket = new WebSocket('wss://'+path+'${ctxPath}/websocket/'+userId);
            // websocket = new WebSocket('ws://localhost:8088/ws/websocket/'+userId);
            //连接成功建立的回调方法
            websocket.onopen = function(event) {
                console.log("Loc MSG: 成功建立连接");
            }

            //接收到消息的回调方法
            websocket.onmessage = function(event) {
                var json = JSON.parse(event.data);
                var  obj = {
                    username: json.name
                    ,avatar: json.avatar
                    ,id: json.id
                    ,type: 'friend'
                    ,content:  json.content
                    ,cid: 0 //消息id，可不传。除非你要对消息进行一些操作（如撤回）
                    ,mine: false //是否我发送的消息，如果为true，则会显示在右方
                    ,fromid:  json.id//消息的发送者id（比如群组中的某个消息发送者），可用于自动解决浏览器多窗口时的一些问题
                    ,timestamp: json.time
                }
                layim.chat({
                    name: json.name //名称
                    ,type: 'friend' //聊天类型
                    ,avatar:  json.avatar //头像
                    ,id: json.id //好友id
                });
                layim.getMessage(obj);
                var id = "#layui-badge-dot-"+json.id;
                $(id).toggleClass("layui-badge-dot",true);
                $("#layui-badge-dot-"+chatId).toggleClass("layui-badge-dot",false);

            }
            //连接发生错误的回调方法
            websocket.onerror = function() {
                console.log("error");
            }


            //连接关闭的回调方法
            websocket.onclose = function() {
                closeWebsocket = true;
                console.log("Loc MSG: 关闭连接");
            }

            //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
            // window.onbeforeunload = function() {
            //     websocket.close();
            // }
        }

    });
</script>
